package com.yangye.pidoublename.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author yangye
 * @date 2019/9/19
 */
@Service
public class GuangDongServiceImpl implements DoubleNameService {
	@Autowired
	private RestTemplate restTemplate;

	private final String QUERY_URL = "http://gdzaj.gd.gov.cn/gdza/web/xsecx/queryXmSl.ignore?xms=";

	/**
	 * 广东接口将返回结果进行了url编码，所以要先url解码
	 * @param name
	 * @return
	 */
	@Override
	public DoubleNameVo findByName(String name) {
		String result = restTemplate.getForObject(QUERY_URL + name, String.class);
		String decodeResult = "";
		try {
			decodeResult = URLDecoder.decode(result, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// 不会发生这种情况
			e.printStackTrace();
		}
		/**
		 * url解码后的返回结果格式
		 * {"杨野":{"2":4,"1":25}}
		 * 1代表男性，2代表女性
		 */
		JSONObject jsonObject = JSON.parseObject(decodeResult).getJSONObject(name);
		Integer man = jsonObject.getInteger("1");
		Integer woman = jsonObject.getInteger("2");
		Integer total = man + woman;
		DoubleNameVo doubleNameVo = new DoubleNameVo();
		doubleNameVo.setName(name);
		doubleNameVo.setProvince(ProvinceEnum.GUANGDONG.getName());
		doubleNameVo.setTotal(total);
		doubleNameVo.setMan(man);
		doubleNameVo.setWoman(woman);
		return doubleNameVo;
	}
}
